package com.keeley.service;

import com.keeley.util.HttpRequest;
import com.keeley.util.PropertiesUtil;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class DefPubService{
    private String cookie;
    private String user="";
    private String user_code="";
    public String login() {
        //SHA1 加密
        String url ="https://www.oschina.net/action/user/hash_login";
        String email = PropertiesUtil.get("email");
        String pwd = PropertiesUtil.get("pwd");
        pwd= DigestUtils.sha1Hex(pwd);

        String param = String.format("email=%s&pwd=%s&verifyCode=&save_login=1", email, pwd);
        cookie=HttpRequest.sendPost(url,param,null);
        Pattern pattern = Pattern.compile("\\[(oscid=.*?);.*?");
        Matcher matcher = pattern.matcher(cookie);
        if(matcher.matches())
            cookie=matcher.group(1);
        return cookie;
    }

    public void initUserCode(){
        //通过修改资料页面爬取user,user_code
        String url="http://my.oschina.net/hongse/admin/profile" ;
        String INPUT = HttpRequest.sendGet(url,cookie);

        String p_user = "name='user'.+?value\\s*=\\s*'([^']*)'";
        String p_user_code = "name='user_code'.+?value\\s*=\\s*'([^']*)'";

        Matcher  matcher =  Pattern.compile(p_user).matcher(INPUT);
        if (matcher.find()) {
            user=matcher.group(1);
        }
        matcher =  Pattern.compile(p_user_code).matcher(INPUT);
        if (matcher.find()) {
            user_code=matcher.group(1);
        }
        System.out.println("user:"+user);
        System.out.println("user_code:"+user_code);
    }

    public boolean send(String context) {
        String url ="http://my.oschina.net/action/tweet/pub";
        String param=String.format("user=%s&user_code=%s&msg=%s",user,user_code,context);
        System.out.println(HttpRequest.sendPost(url,param,cookie));
        return false;
    }

}
